from config.dbDriver import DBDriver
import os


class CouchDB(DBDriver):
    COUCHDB_HOSTS = 'http://127.0.0.1:5984'
    COUCHDB_DATABASES = (
        ('django_couchdb_utils_auth', '%s/authdb' % COUCHDB_HOSTS),
        ('django_couchdb_utils_sessions', '%s/sessionsdb' % COUCHDB_HOSTS),
        ('django_couchdb_utils_cache', '%s/cachedb' % COUCHDB_HOSTS),
    )
    INSTALLED_APPS = ()
    path = os.path.abspath(os.curdir)

    def __init__(self, host, port, username, password, dbName):
        DBDriver.__init__(self)
        self.host = host
        self.port = port
        self.username = username
        self.password = password
        self.dbName = dbName
        self.COUCHDB_HOSTS = 'http://%s:%s' % (host, port)

    def updateEntities(self, path='models/'):
        dirs = os.listdir(os.path.join(self.path, path))
        if 'models.py' in dirs:
            self.addEntity(path)
        for dir in dirs:
            if dir.find('.') == -1:
                self.updateEntities(os.path.join(path, dir))

    def addEntity(self, path):
        self.COUCHDB_DATABASES += ((path.replace('/', '.'), '%s/sp/%s' % (self.COUCHDB_HOSTS, path)),)
        self.INSTALLED_APPS += (path.replace('/', '.'),)

    def connection(self):
        self.updateEntities()
